The Terminal and Program Arguments¶
Introducing the Terminal 💻¶
pwd
ls
cd
- Running python scripts
python hello_world.py
Program Arguments¶
Some programs take arguments
cd directory
python script.py
Can we write a python script that takes arguments?
arg_demo.py
¶
Program arguments are usually separated by spaces.
If you want to include a space in your argument, surround your argument with single quotes.
python arg_demo.py separate arguments
vs
python arg_demo.py 'single argument'
The terminal uses many special symbols for different purposes.
For example, { } ( ) < > | & * $ @ ! ~
all have a special functions.
If you want to include a symbol in a program argument, it's a good idea to wrap it in single quotes.
python arg_demo.py * 7
vs
python arg_demo.py '*' 7
What is sys.argv
?
A list!
What if I just want the "first" argument? How would I get it...?
Indexing¶
hello.py
¶
You can access a specific item in a list (or string or tuple!) using the indexing operator [...]
.
- First item is at
[0]
- Second item is at
[1]
- Etc.
Remember that the first item in sys.argv
(i.e. sys.argv[0]
) is the name of your script!
What happens when you have more commandline arguments than the program uses?
python hello.py John Susan
The extra arguments are ignored.
What happens when you don't supply as many arguments as the program uses?
python hello.py
You will get an IndexError
when python tries to grab a value from a list position that doesn't exist.
repeat.py
¶
The contents of sys.argv
are strings.
Change them to other types as needed.
👨🏼🎨 things.py
¶
Write a program that prompts the user to input things. After they are done, print the list of things.
The number of things to input and the prompt text should be specified on the commandline.
$ python things.py 3 'Fruit or veggy' Fruit or veggy: apple Fruit or veggy: pear Fruit or veggy: broccoli - apple - pear - broccoli
$ python things.py 5 Major Major: Bioinformatics Major: Mathematics Major: Linguistics Major: Vocal Performance Major: History - Bioinformatics - Mathematics - Linguistics - Vocal Performance - History
Key Ideas¶
- The terminal!
- Program arguments,
sys.argv
- Indexing into a list,
[0]
,[1]
, etc.